﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using BLL;
using SMSModels;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace SMSUI.GoodsManager
{
    public partial class FrmOutStoreManager : Form
    {
        private BLL.GoodsManager.OutStoreManager outStoreManager = new BLL.GoodsManager.OutStoreManager();
        private BLL.BaseIndo.GoodsFilesManager goodsFilesManager = new BLL.BaseIndo.GoodsFilesManager();
        private BLL.BaseIndo.StoreManager storeManager = new BLL.BaseIndo.StoreManager();
        private BLL.BaseIndo.SupplierManager supplierManager = new BLL.BaseIndo.SupplierManager();
        private BLL.QueryStatistics.StorageQueryManager storageManager = new BLL.QueryStatistics.StorageQueryManager();

        private IniFile IniFile = new IniFile("./出库方式配置.ini");
        List<Storage> list;
        List<string> printList = new List<string>();

        # region 获取ini配置文件行数
        /// <summary>
        /// 获取ini配置文件行数
        /// </summary>
        /// <param name="FilePath">路径</param>
        /// <returns>返回行数</returns>
        public int GetRows(string FilePath)
        {
            using (StreamReader read = new StreamReader(FilePath, Encoding.Default))
            {
                return read.ReadToEnd().Split('\n').Length;
            }
        }
        #endregion

        public FrmOutStoreManager()
        {
            InitializeComponent();
            //非管理员禁用 修改、删除
            if (Program.currentUser.Power != 0)
            {
                btnRevise.Enabled = false;
                btnDelete.Enabled = false;
            }

            //读取出库方式配置文件到组合框
            for (int i = 0; i < GetRows("./出库方式配置.ini")-2; i++)
            {
                cmbOutStoreType.Items.Add(IniFile.IniReadValue("出库方式",Convert.ToString(i)));
            }
        }
        
        //窗口加载
        private void FrmOutStoreManager_Load(object sender, EventArgs e)
        {
            //绑定出库信息数据到dgv
            DataSet myds = outStoreManager.GetDataSetFromOutStoreTable();
            dgvOutStoreInfo.DataSource = myds.Tables[0];

            //货物现有库存货物信息
            list = storageManager.GetCurrentStorageList();
            //绑定货物编号组合框数据
            cmbGoodsID.DataSource = list;
            cmbGoodsID.DisplayMember = "GoodsID";
            cmbGoodsID.SelectedIndex = -1;
            //绑定货物名称组合框数据
            cmbGoodsName.DataSource = list;
            cmbGoodsName.DisplayMember = "GoodsName";
            cmbGoodsName.SelectedIndex = -1;
            //绑定仓库名称组合框数据
            cmbStoreName.DataSource = list;
            cmbStoreName.DisplayMember = "StoreName";
            cmbStoreName.ValueMember = "StoreID";
            cmbStoreName.SelectedIndex = -1;
            //绑定供货商名称组合框数据
            cmbSupplierName.DataSource = list;
            cmbSupplierName.DisplayMember = "SupplierName";
            cmbSupplierName.ValueMember = "SupplierID";
            cmbSupplierName.SelectedIndex = -1;
            //绑定规格组合框数据
            cmbSpe.DataSource = list;
            cmbSpe.DisplayMember = "Spec";
            cmbSpe.SelectedIndex = -1;
            //绑定计量单位组合框数据
            cmbUnits.DataSource = list;
            cmbUnits.DisplayMember = "Units";
            cmbUnits.SelectedIndex = -1;

            DeleDOC();
        }

        //退出
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //列表单击
        private void dgvOutStoreInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            cmbGoodsID.Text= dgvOutStoreInfo[1, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //货物编号
            cmbGoodsName.Text = dgvOutStoreInfo[2, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //货物名称
            cmbStoreName.Text= dgvOutStoreInfo[4, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //仓库名称
            cmbSupplierName.Text= dgvOutStoreInfo[6, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //供货商名称
            cmbSpe.Text = dgvOutStoreInfo[7, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();   //规格
            cmbUnits.Text = dgvOutStoreInfo[8, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //计量单位
            cmbOutStoreType.Text= dgvOutStoreInfo[9, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //出库方式
            txtOutStoreMonovalent.Text = dgvOutStoreInfo[10, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //出库单价
            txtOutStoreQuantity.Text = dgvOutStoreInfo[11, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //出库数量
            txtOutStoreTotal.Text = dgvOutStoreInfo[12, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //出库总金额
            txtPickUpUnit.Text= dgvOutStoreInfo[13, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //提货单位
            txtConsignee.Text = dgvOutStoreInfo[14, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //提货人
            txtHandler.Text = dgvOutStoreInfo[16, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //经手人
            txtRemarks.Text = dgvOutStoreInfo[17, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString();  //备注
        }
        //出库
        private void btnOutStorage_Click(object sender, EventArgs e)
        {
            if (cmbGoodsID.Text.Length == 0 || cmbGoodsName.Text.Length == 0 || cmbStoreName.Text.Length == 0 || cmbSupplierName.Text.Length == 0 || cmbSpe.Text.Length == 0 || cmbUnits.Text.Length == 0 || cmbOutStoreType.Text.Length == 0 || txtOutStoreMonovalent.Text.Length == 0 || txtOutStoreQuantity.Text.Trim().Length == 0 || txtOutStoreTotal.Text.Trim().Length == 0 || txtHandler.Text.Trim().Length == 0)
            {
                MessageBox.Show("请填写完整！");
            }
            else
            {
                OutStore outStore = new OutStore
                {
                    OutStoreID = "ck" + DateTime.Now.ToString("yyyyMMddHHmmss"), //出库编号
                    GoodsID = cmbGoodsID.Text,  //货物编号
                    StoreID = Convert.ToInt32(cmbStoreName.SelectedValue),  //仓库ID
                    SupplierID = Convert.ToInt32(cmbSupplierName.SelectedValue),  //供货商ID
                    OutStoreType=cmbOutStoreType.Text,  //出库方式
                    OutStoreMonovalent = Convert.ToDouble(txtOutStoreMonovalent.Text.Trim()),  //出库单价
                    OutStoreQuantity = Convert.ToInt32(txtOutStoreQuantity.Text.Trim()),  //出库数量
                    OutStoreTotal = Convert.ToDouble(txtOutStoreTotal.Text.Trim()),  //总金额
                    OutStoreTime = DateTime.Now.ToString("yyyy年MM月dd日HH时mm分"),  //出库时间
                    PickUpUnit=txtPickUpUnit.Text.Trim(),   //提货单位
                    Consignee=txtConsignee.Text.Trim(),   //提货人
                    Handler = txtHandler.Text.Trim(),  //经手人
                    Remarks = txtRemarks.Text.Trim()  //备注
                };

                if (outStoreManager.IsEnough(outStore))   //货物存在于库存中且数量充足
                {
                    if (outStoreManager.OutStore(outStore) >0 && outStoreManager.UpdateStorageOnOutStore(outStore) >0) //插入出库表记录，更新库存表库存数量
                    {
                        MessageBox.Show("出库成功！");
                        FrmOutStoreManager_Load(sender, e);
                    }
                    else
                    {
                        MessageBox.Show("出库失败！请检查！");
                    }
                }
                else     //
                {
                    MessageBox.Show("库存中该货物数量不足！请检查！");
                }
            }
        }
        //修改
        private void btnRevise_Click(object sender, EventArgs e)
        {
            if (cmbGoodsID.Text.Length == 0 || cmbGoodsName.Text.Length == 0 || cmbStoreName.Text.Length == 0 || cmbSupplierName.Text.Length == 0 || cmbSpe.Text.Length == 0 || cmbUnits.Text.Length == 0 || cmbOutStoreType.Text.Length == 0 || txtOutStoreMonovalent.Text.Length == 0 || txtOutStoreQuantity.Text.Trim().Length == 0 || txtOutStoreTotal.Text.Trim().Length == 0 || txtHandler.Text.Trim().Length == 0)
            {
                MessageBox.Show("请填写完整！");
            }
            else
            {
                OutStore outStore = new OutStore
                {
                    OutStoreID = dgvOutStoreInfo[0,dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), //出库编号
                    GoodsID = cmbGoodsID.Text,  //货物编号
                    StoreID = Convert.ToInt32(cmbStoreName.SelectedValue),  //仓库ID
                    SupplierID = Convert.ToInt32(cmbSupplierName.SelectedValue),  //供货商ID
                    OutStoreType = cmbOutStoreType.Text,  //出库方式
                    OutStoreMonovalent = Convert.ToDouble(txtOutStoreMonovalent.Text.Trim()),  //出库单价
                    OutStoreQuantity = Convert.ToInt32(txtOutStoreQuantity.Text.Trim()),  //出库数量
                    OutStoreTotal = Convert.ToDouble(txtOutStoreTotal.Text.Trim()),  //总金额
                    OutStoreTime = DateTime.Now.ToString("yyyy年MM月dd日HH时mm分"),  //出库时间
                    PickUpUnit = txtPickUpUnit.Text.Trim(),   //提货单位
                    Consignee = txtConsignee.Text.Trim(),   //提货人
                    Handler = txtHandler.Text.Trim(),  //经手人
                    Remarks = txtRemarks.Text.Trim()  //备注
                };

                if (outStoreManager.ReviseOutStoreInfo(outStore) > 0) 
                {
                    MessageBox.Show("修改成功！");
                    FrmOutStoreManager_Load(sender, e);
                }
                else
                {
                    MessageBox.Show("修改失败！请检查！");
                }
            }
        }
        //删除
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvOutStoreInfo.CurrentCell != null && dgvOutStoreInfo.CurrentCell.RowIndex != -1)
            {
                OutStore outStore = new OutStore
                {
                    OutStoreID = dgvOutStoreInfo[0, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString()

                };

                if (outStoreManager.DeleteOutStoreInfo(outStore) > 0)
                {
                    MessageBox.Show("删除成功！");
                    FrmOutStoreManager_Load(sender, e);
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
            else
            {
                MessageBox.Show("请在列表中选择要删除的记录！", "提示");
            }
        }
        //选择货物编号
        private void cmbGoodsNum_SelectionChangeCommitted(object sender, EventArgs e)
        {
            List<Storage> list = storageManager.GetListOnSelectGoodsID(cmbGoodsID.Text);
            cmbGoodsName.Text= list[0].GoodsName;  //货物名称
            cmbStoreName.Text = list[0].StoreName;  //仓库名称
            cmbSupplierName.Text = list[0].SupplierName;  //供货商名称
            cmbSpe.Text = list[0].Spec;   //规格
            cmbUnits.Text = list[0].Units;  //计量单位

        }
        //单击改变计算总金额
        private void txtOutStoreMonovalent_TextChanged(object sender, EventArgs e)
        {
            if (txtOutStoreQuantity.Text.Trim().Length != 0 && NumCheck(txtOutStoreMonovalent.Text) && NumCheck(txtOutStoreQuantity.Text))
            {
                txtOutStoreTotal.Text = Convert.ToString(Convert.ToDouble(txtOutStoreMonovalent.Text) * Convert.ToDouble(txtOutStoreQuantity.Text));
            }
        }
        //数量改变计算总金额
        private void txtOutStoreQuantity_TextChanged(object sender, EventArgs e)
        {
            if (txtOutStoreMonovalent.Text.Trim().Length != 0 && NumCheck(txtOutStoreMonovalent.Text) && NumCheck(txtOutStoreQuantity.Text))
            {
                txtOutStoreTotal.Text = Convert.ToString(Convert.ToDouble(txtOutStoreMonovalent.Text) * Convert.ToDouble(txtOutStoreQuantity.Text));
            }
        }
        //数字验证
        public bool NumCheck(string num)
        {
            string pattern = @"^\d+|\d+\.\d+";

            return Regex.IsMatch(num, pattern);
        }
        //添加待打印
        private void 添加到待打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string printNote = string.Format("{0}#{1}#{2}#{3}#{4}#{5}#{6}#{7}#{8}#{9}#{10}#{11}#{12}#{13}", dgvOutStoreInfo[0,dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[1, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[2, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[4, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[6, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[7, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[8, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[9, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[10, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[11, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[12, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[13, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[14, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString(), dgvOutStoreInfo[16, dgvOutStoreInfo.CurrentCell.RowIndex].Value.ToString());
            if (printList.Contains(printNote))  //待打印记录已存在
            {
                return;
            }
            else
            {
                if (printList.Count >= 10)
                {
                    MessageBox.Show("一次只能添加打印10条记录！默认A4纸，太多放不下！");
                    return;
                }
                printList.Add(printNote);
                btnPrint.Text = "打印 " + printList.Count + "条";

            }

        }
        //弹出添加待打印右键菜单
        private void dgvOutStoreInfo_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button==MouseButtons.Right)
            {
                cmsAddPrint.Show(MousePosition.X,MousePosition.Y);
            }
        }
        //打印按钮单击
        private void btnPrint_Click(object sender, EventArgs e)
        {
            //删除存在的打印出库单
            DeleDOC();
            //写入表格数据
            if (printList.Count == 0)
            {
                MessageBox.Show("请在列表中右键添加待打印的出库记录！");
            }
            else
            {
                #region 创建待打印word
                //创建一个文档对象
                Document doc = new Document();
                //添加一个section
                Section section = doc.AddSection();

                //纸张横向
                Section sec = doc.Sections[0];
                sec.PageSetup.Orientation = PageOrientation.Landscape;
                //分别设置四个方向的页边距
                sec.PageSetup.Margins.Top = 12f;
                sec.PageSetup.Margins.Left = 12f;
                sec.PageSetup.Margins.Bottom = 12f;
                sec.PageSetup.Margins.Right = 12f;

                //添加标题
                Paragraph inStoreTitle = section.AddParagraph();
                inStoreTitle.AppendText("出库单");
                //设置标题格式
                ParagraphStyle style1 = new ParagraphStyle(doc);
                style1.Name = "titleStyle";
                style1.CharacterFormat.Bold = true;
                style1.CharacterFormat.TextColor = Color.Black;
                style1.CharacterFormat.FontName = "方正小标宋简体";
                style1.CharacterFormat.FontSize = 24f;
                doc.Styles.Add(style1);
                inStoreTitle.ApplyStyle("titleStyle");
                //标题居中
                inStoreTitle.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                //添加单号
                Paragraph pStrat = section.AddParagraph();
                pStrat.AppendText("单号：ckd" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                //设置单号格式
                ParagraphStyle style12 = new ParagraphStyle(doc);
                style12.Name = "oddNumStyle";
                style12.CharacterFormat.Bold = false;
                style12.CharacterFormat.TextColor = Color.Black;
                style12.CharacterFormat.FontName = "宋体";
                style12.CharacterFormat.FontSize = 12f;
                doc.Styles.Add(style12);
                pStrat.ApplyStyle("oddNumStyle");

                //添加表格
                Table table = section.AddTable(true);
                //指定表格的行数和列数（11行，14列）
                table.ResetCells(11, 14);

                //标题行数组
                string[] tabTitle = { "出库编号", "货物编号", "货物名称", "仓库名称", "供货商", "规格", "计量单位", "出库方式", "出库单价", "出库数量", "出库总额", "提货单位", "提货人", "经手人" };
                //添加表格标题行
                for (int i = 0; i < 1; i++)
                {
                    for (int j = 0; j < 14; j++)
                    {
                        TextRange range = table[i, j].AddParagraph().AppendText(tabTitle[j]);
                        range.CharacterFormat.FontName = "黑体";
                        range.CharacterFormat.FontSize = 12;
                        range.CharacterFormat.TextColor = Color.Black;
                        range.CharacterFormat.Bold = false;
                        table[i, j].Paragraphs[0].Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;  //水平居中
                        table[i, j].CellFormat.VerticalAlignment = VerticalAlignment.Middle;    //垂直居中
                    }
                }

                //遍历打印列表并插入表格数据
                for (int i = 0; i < printList.Count; i++)
                {
                    string[] arr = printList[i].Split('#');
                    for (int j = 0; j < 14; j++)
                    {
                        TextRange range = table[i + 1, j].AddParagraph().AppendText(arr[j]);
                        range.CharacterFormat.FontName = "宋体";
                        range.CharacterFormat.FontSize = 10;
                        range.CharacterFormat.TextColor = Color.Black;
                        range.CharacterFormat.Bold = false;
                        table[i + 1, j].CellFormat.VerticalAlignment = VerticalAlignment.Middle;    //垂直居中
                    }
                }
                //添加签字栏
                Paragraph pEnd = section.AddParagraph();
                pEnd.AppendText("制单人：              审核人：              日期：    年  月  日");
                //设置签字栏格式
                ParagraphStyle style13 = new ParagraphStyle(doc);
                style13.Name = "endLineStyle";
                style13.CharacterFormat.Bold = false;
                style13.CharacterFormat.TextColor = Color.Black;
                style13.CharacterFormat.FontName = "宋体";
                style13.CharacterFormat.FontSize = 12f;
                doc.Styles.Add(style13);
                pEnd.ApplyStyle("endLineStyle");

                //保存文档
                doc.SaveToFile("./outStoreDoc.docx", FileFormat.Docx2013);
                #endregion

                System.Threading.Thread.Sleep(1000);

                #region 开始打印
                //初始化PrintDialog实例
                PrintDialog dialog = new PrintDialog();

                //设置打印对话框属性
                dialog.AllowPrintToFile = true;
                dialog.AllowCurrentPage = true;
                dialog.AllowSomePages = true;

                //设置文档打印对话框
                doc.PrintDialog = dialog;

                //显示打印对话框并点击确定执行打印
                System.Drawing.Printing.PrintDocument printDoc = doc.PrintDocument;
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    printDoc.Print();
                }
                DeleDOC();
                #endregion
            }
        }


        /// <summary>
        /// 删除outStoreDoc.docx文件
        /// </summary>
        public void DeleDOC()
        {
            if (System.IO.File.Exists("./outStoreDoc.docx"))
            {
                System.IO.File.Delete("./outStoreDoc.docx");
            }
        }
        //弹出清空待打印菜单
        private void btnPrint_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button==MouseButtons.Right)
            {
                cmsClearPrintList.Show(MousePosition.X,MousePosition.Y);
            }
        }
        //单击清空菜单
        private void 清空待打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            printList.Clear();
            btnPrint.Text = "打印";
        }
    }
}
